package sort_algorithms;

import main.SortDemo;

import datastructures.Datum;
import datastructures.Status;

/**
 * BubbleSort as found in psuedocode on http://en.wikipedia.org/w/index.php?title=Bubble_sort&oldid=359021456
 * 
 * @author kf6kjg
 * 
 */
public class BubbleSort extends AbstractSorter {
  private int   n;
  
  private int   i;
  
  private Datum datum_left;
  
  private Datum datum_right;
  
  /*
   * (non-Javadoc)
   * 
   * @see sort_algorithms.ISorter#step()
   */
  @Override
  public void step() {
    // Reset the old ones.
    this.datum_left.status = this.datum_right.status = Status.DEFAULT;
    
    // Get the new ones
    this.datum_left = SortDemo.data.get(i);
    this.datum_right = SortDemo.data.get(i + 1);
    
    // Set the new status
    this.datum_left.status = Status.COMPARE_LEFT;
    this.datum_right.status = Status.COMPARE_RIGHT;
    
    if (this.datum_left.compareTo(this.datum_right) > 0) {
      // Swap the elements
      SortDemo.data.setElementAt(this.datum_right, i);
      SortDemo.data.setElementAt(this.datum_left, i + 1);
    }
    
    if (++i >= n - 1) {
      i = 0;
      --n;
    }
  }
  
  /*
   * (non-Javadoc)
   * 
   * @see sort_algorithms.AbstractSorter#isSorted()
   */
  @Override
  public boolean isSorted() {
    if (n <= 0) {
      // Reset the last ones.
      this.datum_left.status = this.datum_right.status = Status.DEFAULT;
      
      return true;
    }
    
    return false;
  }
  
  /*
   * (non-Javadoc)
   * 
   * @see sort_algorithms.AbstractSorter#getName()
   */
  @Override
  public String getName() {
    return "Bubble Sort - Wikipedia";
  }
  
  /*
   * (non-Javadoc)
   * 
   * @see sort_algorithms.AbstractSorter#reset()
   */
  @Override
  public void reset() {
    this.n = SortDemo.data.size();
    this.i = 0;
    
    this.datum_left = SortDemo.data.get(i);
    this.datum_right = SortDemo.data.get(i + 1);
  }
}
